<?php

/* 
 * 商家模型
 * @author wyb
 */
namespace Qwadmin\Model;
class ApiModel extends BaseModel {
	
	 public $url="";
	 public $api;
	 function __construct($api_id=1)
	 {
        
		$api=M('shop_api')->where('id='.$api_id)->select();    
        // $obj=new ReflectionClass($api)
		$this->api=$api[0];
		$this->url=$this->api['url'];
	
		
	 }
    
    //自动组合入库数据
    protected $_auto = array(
        array('create_time' , 'time' , 1 , 'function' ),
        array('status' , '1' , 1),
        
    );

    
    
    //插入前操作
    protected function _before_insert(&$data, $options) {
        $data['key'] = $this->__authKey();
        
    }
    
    
    /**
     * 自动生成key
     */
    private function __authKey() {
        $str = 'ABC123456DEHJHIklmnopqrstJKL0123456789MNOPQRSTklmnopqrstUVWXY0123456789Zabcdefghijklmnopqrstuvwxyz0123456789';
        $len_str = strlen( $str );
        $key_str = '';
        for( $i = 1; $i <= 50; $i++ ) {
            $key_str .= $str[ rand( 0 , $len_str - 1 ) ];
        }
        if( $this->where(array('key' => $key_str ) )->find() ) {
            return $this->__authKey();
        }
        return $key_str;
    }
	
	
	 public function post($url, $post_data = '', $timeout = 60){
  
        $ch = curl_init();
      // $this_header = array("content-type: text/html; charset=UTF-8");
        curl_setopt ($ch, CURLOPT_URL, $url);
       // curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
        curl_setopt ($ch, CURLOPT_POST, 1);
  
        if($post_data != ''){
  
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  
        }
  
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
  
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  
        curl_setopt($ch, CURLOPT_HEADER, false);
  
        $file_contents = curl_exec($ch);
		
		if(curl_getinfo ( $ch,CURLINFO_SIZE_DOWNLOAD)==0){
			//curl_close($ch);
			//$this->post($url,$post_data,$timeout);
		};
       // echo "<br>";
       // var_dump(curl_getinfo ( $ch));

        curl_close($ch);
  
        return $file_contents;
    }
	
	 public function post_json($url, $post_data = '', $timeout = 60){
  
        $ch = curl_init($url);
        curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt( $ch, CURLOPT_POSTFIELDS,  json_encode($post_data ) );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' ) );



       // curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
  
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  
        //curl_setopt($ch, CURLOPT_HEADER, false);
  
        $file_contents = curl_exec($ch);

       // echo "<br>";
       //var_dump(curl_getinfo ($ch));

        curl_close($ch);
        return $file_contents;
    }
	
	
	
}

